/* eslint-disable */
import axios from 'axios'
import router from '@/router'
import { Toast } from 'vant'
import { Dialog } from 'vant'

/**
* 定义请求常量
* TIME_OUT、ERR_OK
*/

const TIME_OUT =38000;    // 请求超时时间
const PRODURL = 'http://ms.qyera.cn/web'
const DEVURL = '/apis'
var API_HOST = ''

process.env.NODE_ENV==='development' ? API_HOST = DEVURL : API_HOST = PRODURL

// 请求超时时间
axios.defaults.timeout = TIME_OUT

// 封装请求拦截
axios.interceptors.request.use(config => {
		// 发起请求，取消掉当当前正在进行的相同请求
		return config
	},
	error => {
		return Promise.reject(error)
	}
)
// 封装响应拦截，判断token是否过期
axios.interceptors.response.use(
  response => {
  	return response
  },
  error  => {
  	if (error.response) {
  		switch (error.response.status) {
  			case 400:
  				error.message = 'Status:400'
  				break;
  			case 401:
  				error.message = 'Status:401'
  				break;
  			case 403:
  				error.message = 'Status:403'
  				break;
  			case 404:
  				error.message = 'Status:404'
					// router.toReplace('/error/404', {err: '内容不存在或者已被删除'})
  				break;
  			case 405:
  				error.message = 'Status:405'
  				break;
  			case 408:
  				error.message = 'Status:408'
  				break;
  			case 500:
  				error.message = 'Error:500'
					// router.toReplace('/error/404', {err: '服务器出错咯!'})
  				break;
  			case 501:
  				error.message = 'Status:501'
  				break;
  			case 502:
  				error.message = 'Status:502'
  				break;
  			case 503:
  				error.message = 'Status:503'
  				break;
  			case 504:
  				error.message = 'Network Timeout 504'
  				break;
  			default:
  				error.message = `ERROR:${error.response.status}`
					break;
  		}
  	}
		else if(error.request){
			// 捕获超时请求
			error.message = 'TimeOut';
		}
		return Promise.reject(error);
  }
)
// 封装请求
export function Axios(requestUrl, params, type = 'POST') {
  return new Promise((resolve,reject) => {
    axios({
      url: API_HOST + requestUrl,
      method: type,
      data: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
			Toast.clear()
			Dialog({
			  message: '网络开小差啦~',
			  closeOnClickOverlay: true
			})
      reject(err);
    })
  })
}
